package org.kazuhiko.rpg.server.net.packet.handler;

import java.util.Map;

import org.kazuhiko.rpg.server.net.RPGSession;
import org.kazuhiko.rpg.server.net.packet.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PacketHandlerManager<SessionType extends RPGSession>
{
	private static final Logger logger = LoggerFactory.getLogger( PacketHandlerManager.class );
	
	@SuppressWarnings("rawtypes")
	private PacketHandler[] handlers = new PacketHandler[256];
	
	@SuppressWarnings("rawtypes")
	public PacketHandlerManager( Map<Integer, String> map )
	{
		try
		{
			Map<Integer, String> hndlers = map;
			for( Map.Entry<Integer, String> handler : hndlers.entrySet() )
			{
				this.handlers[handler.getKey()] = ( PacketHandler) Class.forName( handler.getValue() ).newInstance();
			}
		}
		catch( Exception ex )
		{
			throw new ExceptionInInitializerError( ex );
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void handlePacket( SessionType session, Packet packet )
	{
		PacketHandler handler = handlers[packet.getDefinition().getId()];
		
		if( handler != null )
		{
			handler.handlePacket( session, packet );
		}
		else
		{
			logger.warn( "Unhandled packet: " + packet + "." );
		}
	}
}
